using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
	
	public delegate void PainEvent(float painAmount);
	public delegate void PainLevelEvent(float painLevel);
	public delegate void LevelEndEvent();
	
	public static PainEvent OnPain;
	public static PainLevelEvent OnPainLevelChange;
	public static LevelEndEvent OnLevelWin;
	public static LevelEndEvent OnLevelLose;
	
	public float points = 0;
	public float maxPoints = 100;
	
	private float painLevel = 0;
	public float PainLevel
	{
		get {return painLevel;}
		set {
			float oldPainLevel = painLevel;
			painLevel = Mathf.Max(0, Mathf.Min(maxPainLevel, value));
			if(OnPainLevelChange != null && oldPainLevel != painLevel)
				OnPainLevelChange(painLevel);
		}
	}
	public float maxPainLevel = 100;
	
	private static GameController sInstance;
	public static GameController instance
	{
		get {
			if(sInstance == null)
				Debug.LogError("GameController does not exist in scene.");
			return sInstance;
		}
	}
	
	void Awake ()
	{
		if(sInstance != null)
			Debug.LogError("Multiple GameControllers exist in scene.");
		sInstance = this;
	}
	
	void OnDestroy()
	{
		sInstance = null;
	}
	
	void Start () 
	{
		StartCoroutine(recover());
	}
	
	IEnumerator recover()
	{
		while(true)
		{
			PainLevel--;
			yield return new WaitForSeconds(0.1f);
		}
	}
	
	public void Pain()
	{
		points += 5;
		if(points >= 100)
		{
			StartCoroutine(win());
			return;
		}
		
		PainLevel += 20;
		if(PainLevel >= 100)
		{
			StartCoroutine(lose());
			return;
		}
		
		print(painLevel/maxPainLevel);
		
		if(OnPain != null)
			OnPain(painLevel/maxPainLevel);
	}
	
	IEnumerator win()
	{
		if(OnLevelWin != null)
			OnLevelWin();
		
		yield return new WaitForSeconds(2);
		
		Application.LoadLevel(0);
	}
	
	IEnumerator lose()
	{
		if(OnLevelLose != null)
			OnLevelLose();
		
		yield return new WaitForSeconds(2);
		
		Application.LoadLevel(0);
	}
}
